package action;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;

import proxy.ProxyFactory;
import service.ExpressService;
import service.ExpressServiceInterface;
import utils.AlipayHelper;

import beans.Agent;
import beans.Company;
import beans.Express;
import beans.LogPay;
import beans.LogPayPackage;
import beans.RechargeConfig;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import dao.AgentDao;
import dao.CompanyDao;
import dao.CourierDao;
import dao.ExpenseDao;
import dao.ExpressDao;
import dao.LogPayDao;
import dao.LogPayPackageDao;
import dao.RechargeConfigDao;

@SuppressWarnings("serial")
public class ExpressAction extends ActionSupport implements ModelDriven<Express>{
	List<Express> expressBranchs;
	List<Company> companies;
	List<LogPay> logPays;
	List<LogPayPackage> logPayPackages;
	List<RechargeConfig> rechargeConfigs;

	ExpressDao expressBranchDao = new ExpressDao();
	CompanyDao companyDao = new CompanyDao();
	CourierDao courierDao = new CourierDao();
	AgentDao agentDao = new AgentDao();
	ExpenseDao expenseDao = new ExpenseDao();
	LogPayDao logPayDao = new LogPayDao();
	LogPayPackageDao logPayPackageDao = new LogPayPackageDao();
	RechargeConfigDao rechargeConfigDao = new RechargeConfigDao();
	
    private int rows;// easyui页大小
    private int page;// easyui当前页
    private String returnType;// 返回类型
    private String pageName;//返回页面
    private String ids;//删除id集合
	
	private int expressBranchID;
	private int company = 0;
	private int expressId;
	private int agentID;
	private int status;
	private int payConfID;// 充值配置id
	private int payType;// 充值类型
	private BigDecimal money;
	private BigInteger mobileNum;
	private String expressProvince;
	private String expressCity;
	private String accountPwd;
	private String serialNum;
	private Express express = new Express();
	private RechargeConfig rechargeConfig = new RechargeConfig();
	private LogPay logPay = null;
	
	Map<String, Object> message = new HashMap<String, Object>();
	private Map<String, Object> expressMap;
	
	ActionContext actionContext = ActionContext.getContext();
    Map<String, Object> session = actionContext.getSession();
    Agent agent = (Agent) session.get("admin");
    
    ExpressServiceInterface expressService = (ExpressServiceInterface) ProxyFactory.getProxyInstance(new ExpressService());
    
    /**
     * 
     * 返回页面
     * @author Devil Zheng
     * @created 2015-9-15 下午4:50:13
     * @return
     */
	public String returnJSP() {
        return pageName;
    }
	
	/**
	 * 
	 * 获取列表
	 * @author Devil Zheng
	 * @created 2015-9-15 下午4:50:04
	 * @return
	 */
    public String getExpressPage() {
        if (returnType.equals("json")) {
            expressMap = new HashMap<String, Object>();
            expressMap.put("total", expressService.getExpressNumber(agent));
            expressMap.put("rows", expressService.getExpressPage(agent, rows, page));
            return "jsonSuccess";
        }else{
            return "expressList";
        }
    }
    
    /**
     * 
     * 删除
     * @author Devil Zheng
     * @created 2015-9-15 下午4:59:57
     * @return
     */
    public String deleteExpress(){//要删除下属快递员和收费点
        expressMap = new HashMap<String, Object>();
        try {
            expressService.deleteExpress(ids);
            expressMap.put("success", true);
            expressMap.put("msg", "删除成功");
        } catch (Exception e) {
            expressMap.put("success", false);
            expressMap.put("msg", "删除失败"+e.toString());
        }
        return "jsonSuccess";
    }
	
	public String getByExpressId() {
		express = expressBranchDao.getExpressBranch(expressId);
		expressBranchs = new ArrayList<Express>();
		expressBranchs.add(express);
		return "getExpress";
	}
	/**
	 * 编辑快递网点
	 * 
	 * @return
	 */
	public String editExpress() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		Express e = expressBranchDao.getExpressBranch(expressBranchID);
		/*if (mobileNum != null
				&& CheckPhoneHelper.isMobileNO(mobileNum.toString())) {
			express.setCourier(courierDao.getByMobileNum(mobileNum));
		}*/
		express.setCompany(companyDao.getCompanyById(company));
		express.setExpressProvince(expressProvince);
		express.setExpressCity(expressCity);
		express.setExpressId(expressBranchID);
		express.setAgent(admin);
		express.setExpressBalance(e.getExpressBalance());
		if (express.getPayway() == 0) {
			if (e.getExpressBalance().compareTo(express.getOverdue()) >= 0) {
				express.setStatus(0);
			} else {
				express.setStatus(1);
			}
		} else {
			express.setStatus(0);
		}
		expressBranchDao.edit(express);
		return "success";
	}

	/**
	 * 启用/停用网点
	 * 
	 * @return
	 */
//	public String changeStatus() {
//		expressBranchDao.changeStatus(expressBranchID, status);
//		return getAllExpress();
//	}
	
	/**
	 * 充值界面
	 * 
	 * @return
	 */
	public String payExpressPage() {
		express = expressBranchDao.getExpressBranchById(expressBranchID);
		return "payExpressPage";
	}
	
	/**
	 * 获取充值配置列表
	 * @return
	 */
	public String getPayConfig() {
		express = expressBranchDao.getExpressBranch(expressId);
		rechargeConfigs = rechargeConfigDao.getAll(express);
		return "payConfig";
	}
	
	/**
	 * 删除配置
	 * @return
	 */
	public String deletePayConf(){
		rechargeConfig = rechargeConfigDao.getConfById(payConfID);
		rechargeConfigDao.delete(rechargeConfig);
		return getPayConfig();
	}

	/**
	 * 新增快递网点
	 * 
	 * @return
	 */
	public String registerExpress() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		/*if (CheckPhoneHelper.isMobileNO(mobileNum.toString())) {
			express.setCourier(courierDao.getByMobileNum(mobileNum));
		}*/
		express.setCompany(companyDao.getCompanyById(company));
		express.setExpressProvince(expressProvince);
		express.setExpressCity(expressCity);
		express.setAgent(admin);
		express.setExpressBalance(new BigDecimal(0));
		express.setStatus(0);
		expressBranchDao.save(express);
		return "success";
	}
	
	/**
	 * 新增充值配置
	 * @return
	 */
	public String registerConf(){
		rechargeConfig.setExpress(expressBranchDao.getExpressBranch(expressId));
		rechargeConfigDao.save(rechargeConfig);
		return getPayConfig();
	}
	
	/**
	 * 检测财务密码
	 * 
	 * @return
	 */
	public String checkAccountPwd() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		String pwd = admin.getAccountPwd();
		// accountPwd=MD5Helper.getMD5Str(accountPwd);
		if (pwd.equals(accountPwd)) {
			message.put("result", "success");
		} else {
			message.put("result", "failed");
		}
		return "jsonResult";
	}

	/**
	 * 获取所有快递网点
	 */
	public String getAllExpressCompany() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		companies = companyDao.getAllcompany();
		if (admin.getDeduction() == 1) {
			return "success";
		} else {
			return "fail";
		}
	}

	/**
	 * 通过ID获取网点
	 */
	public String getExpressBranchList() {
		express = expressBranchDao.getExpressBranch(expressId);
		return "success";
	}

	/**
	 * 获取该快递网点充值详情
	 * 
	 * @return
	 */
	public String getExpressPayDetail() {
		logPays = logPayDao.getByExpBranchID(expressBranchID);
		return "payment";
	}

	/**
	 * 获取快递网点扣费详情
	 * 
	 * @return
	 */
	public String getExpressPayPackageDetail() {
		logPayPackages = logPayPackageDao.getByExpBranchID(expressBranchID);
		return "logPayPackage";
	}

	/**
	 * 获取快递网点详情
	 * 
	 * @return
	 */
	public String getExpressDetail() {
		express = expressBranchDao.getExpressBranchById(expressId);
		return "details";
	}

	/**
	 * 通过ID获取网点
	 */
	public String getExpressById() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		getAllExpressCompany();
		express = expressBranchDao.getExpressBranch(expressId);
		if (admin.getDeduction() == 1) {
			return "success";
		} else {
			return "fail";
		}
	}

	/**
	 * 获取所有网点和公司
	 */
	public String getCompanyAndBranch() {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent admin = (Agent) session.get("admin");
		companies = companyDao.getAllcompany();
		if (company != 0) {
			expressBranchs = expressBranchDao.getCompanyExpressBranch(admin,company);
			return "jsonSuccess";
		} else {
			return "success";
		}

	}

	/**
	 * 充值缴费
	 * @throws Exception 
	 * @throws DocumentException 
	 */
	public String payIn() throws DocumentException, Exception {
		ActionContext actionContext = ActionContext.getContext();
		Map<String, Object> session = actionContext.getSession();
		Agent agent = (Agent) session.get("admin");
		express = expressBranchDao.getExpressBranch(expressId);
		rechargeConfigs = rechargeConfigDao.getAll(express,money);
		if(agent.getRecharge()==0){
			serialNum = AlipayHelper.getSerialNum("YB");
		}else{
			serialNum = AlipayHelper.getSerialNum(agent.getName());
		}
		BigDecimal zero = new BigDecimal(0);
		Timestamp timestamp = new Timestamp(new Date().getTime());
		String str = "";
		if(money.compareTo(zero)<0){
			str = "充错，扣除多充费用！";
		}
//		if (payType == 1) {
			logPay = new LogPay(timestamp, agent,
					express, money,zero, payType, serialNum, str, "success");
			logPayDao.save(logPay);
			BigDecimal temp = express.getExpressBalance().add(money);
			if (express.getPayway() == 0 && temp.compareTo(zero) > 0) {
				express.setStatus(0);
			}
			if (express.getPayway() == 0 && temp.compareTo(zero) <= 0) {
				express.setStatus(1);
			}
			express.setExpressBalance(temp);
			expressBranchDao.edit(express);
			agent.setBalance(agent.getBalance().add(money));
			agentDao.edit(agent);
			return "success";
//		} else if (payType == 0) {
//			give = money.multiply(rechargeConfigs.get(0).getProportion().subtract(one));
//			logPay = new LogPay(new Timestamp(new Date().getTime()), admin,
//					express, money,give, payType, serialNum, "", "wait");
//			logPayDao.save(logPay);
//			HttpServletResponse response = ServletActionContext.getResponse();
//			String url = AlipayHelper.buildURL(agent,serialNum, express.getCourier()
//					.getMobileNum(), express.getExpressName(), money);
//			response.sendRedirect(url);
//			// response.sendRedirect("alipayapi.jsp?serialNum=" + serialNum
//			// + "&money=" + money + "&phoneNum=" +
//			// express.getCourier().getMobileNum());
//			return null;
//		} else {
//			return null;
//		}
	}

	public List<Express> getExpressBranchs() {
		return expressBranchs;
	}

	public void setExpressBranchs(List<Express> expressBranchs) {
		this.expressBranchs = expressBranchs;
	}

	public List<Company> getCompanies() {
		return companies;
	}

	public void setCompanies(List<Company> companies) {
		this.companies = companies;
	}

	public int getExpressBranchID() {
		return expressBranchID;
	}

	public void setExpressBranchID(int expressBranchID) {
		this.expressBranchID = expressBranchID;
	}

	public Express getExpress() {
		return express;
	}

	public void setExpress(Express express) {
		this.express = express;
	}

	public int getCompany() {
		return company;
	}

	public void setCompany(int company) {
		this.company = company;
	}

	public int getExpressId() {
		return expressId;
	}

	public void setExpressId(int expressId) {
		this.expressId = expressId;
	}

	public String getExpressProvince() {
		return expressProvince;
	}

	public void setExpressProvince(String expressProvince) {
		this.expressProvince = expressProvince;
	}

	public String getExpressCity() {
		return expressCity;
	}

	public void setExpressCity(String expressCity) {
		this.expressCity = expressCity;
	}

	public int getAgentID() {
		return agentID;
	}

	public void setAgentID(int agentID) {
		this.agentID = agentID;
	}

	public BigInteger getMobileNum() {
		return mobileNum;
	}

	public void setMobileNum(BigInteger mobileNum) {
		this.mobileNum = mobileNum;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public List<LogPay> getLogPays() {
		return logPays;
	}

	public void setLogPays(List<LogPay> logPays) {
		this.logPays = logPays;
	}

	public List<LogPayPackage> getLogPayPackages() {
		return logPayPackages;
	}

	public void setLogPayPackages(List<LogPayPackage> logPayPackages) {
		this.logPayPackages = logPayPackages;
	}
	public List<RechargeConfig> getRechargeConfigs() {
		return rechargeConfigs;
	}
	public void setRechargeConfigs(List<RechargeConfig> rechargeConfigs) {
		this.rechargeConfigs = rechargeConfigs;
	}
	public int getPayConfID() {
		return payConfID;
	}
	public void setPayConfID(int payConfID) {
		this.payConfID = payConfID;
	}
	public RechargeConfig getRechargeConfig() {
		return rechargeConfig;
	}
	public void setRechargeConfig(RechargeConfig rechargeConfig) {
		this.rechargeConfig = rechargeConfig;
	}
	public String getAccountPwd() {
		return accountPwd;
	}
	public void setAccountPwd(String accountPwd) {
		this.accountPwd = accountPwd;
	}
	public Map<String, Object> getMessage() {
		return message;
	}
	public void setMessage(Map<String, Object> message) {
		this.message = message;
	}
	public LogPay getLogPay() {
		return logPay;
	}
	public void setLogPay(LogPay logPay) {
		this.logPay = logPay;
	}
	public BigDecimal getMoney() {
		return money;
	}
	public void setMoney(BigDecimal money) {
		this.money = money;
	}
	public String getSerialNum() {
		return serialNum;
	}
	public void setSerialNum(String serialNum) {
		this.serialNum = serialNum;
	}
	public int getPayType() {
		return payType;
	}
	public void setPayType(int payType) {
		this.payType = payType;
	}

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public String getReturnType() {
        return returnType;
    }

    public void setReturnType(String returnType) {
        this.returnType = returnType;
    }

    public String getPageName() {
        return pageName;
    }

    public void setPageName(String pageName) {
        this.pageName = pageName;
    }

    public Map<String, Object> getExpressMap() {
        return expressMap;
    }

    public void setExpressMap(Map<String, Object> expressMap) {
        this.expressMap = expressMap;
    }
    
    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    @Override
    public Express getModel() {
        return express;
    }

}
